<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>入库审核</title>
</head>
<body>
	<script type="text/javascript">

		$(function() {
			
			//入库审核
			$('#audit-dg').datagrid({
				url : 'findother-indent',
				pagination : true,
				pageNumber : 1,
				pageSize : 10,
				singleSelect: true,
				pageList : [ 10, 20 ],
				columns : [ [
					{field : 'indent_id',				title : '采购单号',		width : 210}, 
					{field : 'indent_time',				title : '采购日期',		width : 205,formatter:comFormatDate}, 
					{field : 'indent_people',			title : '负责人',			width : 210},  
					{field : 'indent_allquantity',		title : '总数量',			width : 210}, 
					{field : 'indent_allmoney',			title : '总金额',			width : 210}, 
					{field : 'supplier_number',			title : '供应商',			hidden:true}
				] ],
				onDblClickRow : function(rowIndex, rowData) {
					$("#inaudit-win").window("open");
					//获取采购单号
					$("#audit-cgdh").textbox('setValue',rowData.indent_id);
					//获取总金额
					$("#audit-cgsj").textbox('setValue',rowData.indent_allmoney);
					//获取负责人
					$("#audit-fzr").textbox('setValue',rowData.indent_people);
					//获取采购时间
					var st=rowData.indent_time;
					var ts=CurentTime(st);
					$("#audit-rukushij").textbox('setValue',ts);
					//获取供应商
					$("#audit-gyss").textbox('setValue',rowData.supplier_number);
					
					//采购单号
					var indentid = $("#audit-cgdh").textbox("getValue");
					
					//根据采购详情获取采购单号
					$.ajax({  
                        url: 'findall-indentdetails',  
                        data:{'indentid':indentid},
                        type: 'POST',  
                        dataType:"json",
					 	success: function (data) {  
					 				//遍历数据前清空datagrid数据
					 				$('#inaudit-dg').datagrid('loadData',{total:0,rows:[]});
					 				//循环订单商品数据
					                for ( var machine in data.result) {
					                	if(data.result[machine].drugbatch==null){
					                		data.result[machine].drugbatch=0;
					                	}else{
					                		data.result[machine].drugbatch=data.result[machine].drugbatch;
					                	}
					                    var row_data = {
					    					'drug_number' : data.result[machine].drug_number,
					                        'drug_name' : data.result[machine].drug_name,
					                        'drug_standard' : data.result[machine].drug_standard,
					                        'drug_purchase_price' : data.result[machine].drug_purchase_price,
					                        'indent_details_quantity' : data.result[machine].indent_details_quantity,
					                        'in_details_quantity' : data.result[machine].indent_details_quantity,
					                        'in_details_jine' : data.result[machine].drug_purchase_price*data.result[machine].indent_details_quantity ,
					                        'drugbatch' : data.result[machine].drugbatch+1,
					                        'drug_origin' : data.result[machine].drug_origin,
					                        'inventory_number' : data.result[machine].inventory_number
					                    };
					                    $('#inaudit-dg').datagrid('appendRow', row_data);
					                }
					     }, 				     
                        Error: function () {  
                            alert(Error);  
                        }                   
                    });    
					
				}
			});

			//入库验收
			$('#inaudit-dg').datagrid({
				url : '',
				pagination : true,//显示分页
				pageNumber : 1,
				pageSize : 10,//页大小
				singleSelect: true,
				pageList : [ 10, 20 ],
				columns : [ [ 
					{field : 'drug_number',					title : '药品编号',		width : 130}, 
					{field : 'drug_name',					title : '药品名称',		width : 135}, 
					{field : 'drug_standard',				title : '规格',			width : 125}, 
					{field : 'drug_purchase_price',			title : '单价(元)',		width : 90},
					{field : 'indent_details_quantity',		title : '采购数量',		width : 120},
					{field : 'in_details_quantity',			title : '入库数量',		width : 110,editor:'numberbox'}, 
					{field : 'in_details_jine',				title : '金额',			width : 110}, 
					{field : 'drugbatch',					title : '批次',			width : 75},
					{field : 'dataTime',					title : '生产日期',		width : 132 ,editor:"datebox"},
					{field : 'drug_origin',					title : '保质期',			width : 95,hidden:true},
					{field : 'inventory_number',			title : '库存编号',		width : 75,hidden:true} 
				] ],
				onDblClickCell: function(index,field,value){
			        $(this).datagrid('beginEdit', index);
			        var ed = $(this).datagrid('getEditor', {index:index,field:field});
			        if (ed.editing) {  
			            $(this).edatagrid('editRow', index);  
			            focusEditor(field);  
			            //以下是我添加的代码  
			            var currentEdatagrid = $(this);  
			            $('.datagrid-editable .textbox-numberbox').bind('keydown', function(e){  
                            var code = e.keyCode || e.which;  
                            if(code == 13){  
                                $('#inaudit-dg').datagrid('acceptChanges');  
                                $('#inaudit-dg').datagrid('endEdit', index);  
                            }  
			            });  
			            //添加代码结束  
			        }  
			        if (opts.onDblClickCell) {  
			            opts.onDblClickCell.call(target, index, field,value);  
			        }  
			    },
			    onBeforeEdit:function(index,row){
			        row.editing = true;
			        $('#inaudit-dg').datagrid('refreshRow', index);
			    },
				onCancelEdit:function(index,row){
				    row.editing = false;
				    $('#inaudit-dg').datagrid('refreshRow', index);
				}
			});
			
			//系统当前日期以后的日期、禁止选择
			
			
			// 时间戳
			function CurentTime(){
		  
		        var now = new Date();
		       
		        var year = now.getFullYear();       //年
		        var month = now.getMonth() + 1;     //月
		        var day = now.getDate();            //日
		       
		        var hh = now.getHours();            //时
		        var mm = now.getMinutes();          //分
				var ss = now.getSeconds();			//秒
		       
		        var clock = year + "-";
		       
		        if(month < 10)
		            clock += "0";
		       
		        clock += month + "-";
		       
		        if(day < 10)
		            clock += "0";
		           
		        clock += day + " ";
		       
		        if(hh < 10)
		            clock += "0";
		           
		        clock += hh + ":";
		        if (mm < 10) clock += '0'; 
		        clock += mm + ":"; 
				
		        if (ss < 10) clock += '0'; 
		        clock += ss; 
		        return(clock); 
			}
			
			//取消入库验收
			$("#cancel-audit").click(function(){
				$("#inaudit-win").window("close");
			});
			
			//确认入库验收
			$("#save-audit").click(function(){
				var rows = $("#inaudit-dg").datagrid("getRows");
				var pand =true;
				var panduan =true;
				var pandds =true;
				var pandfd =true;
				var pandasd=true;
				for(var i = 0; i < rows.length; i++){
					//判断有无生产日期
					if(rows[i]["dataTime"]==null||rows[i]["dataTime"]==""){
						pand = false ;
					}
					//判断入库数量是否大于采购数量
					if(rows[i]["indent_details_quantity"] < rows[i]["in_details_quantity"]){
						pandds =false;
					}
					//判断入库数量是否小于零
					if(rows[i]["in_details_quantity"] < 0){
						pandfd =false;
					}
					//判断入库数量是否为空
					if(rows[i]["in_details_quantity"]==""){
						pandasd=false;
					}
					//退药
					if(rows[i]["indent_details_quantity"] != rows[i]["in_details_quantity"]){
						panduan =false;
					}
					
				}
				
				if(pand==false){
					$(".drugoneb").text("生产日期不能为空");
			 		 //清空文本
			 		$("#DRUGONEb").window('open');
			  	 	//三秒之后自动消失
			   		setTimeout(function(){
			    	 	$("#DRUGONEb").window('close');															    	 	
					}, 1500);
				}else if(pandds==false){
					$(".drugoneb").text("入库数量不能大于采购数量");
			 		 //清空文本
			 		$("#DRUGONEb").window('open');
			  	 	//三秒之后自动消失
			   		setTimeout(function(){
			    	 	$("#DRUGONEb").window('close');															    	 	
					}, 1500);
				}else if(pandfd==false){
					$(".drugoneb").text("入库数量不能小于零");
			 		 //清空文本
			 		$("#DRUGONEb").window('open');
			  	 	//三秒之后自动消失
			   		setTimeout(function(){
			    	 	$("#DRUGONEb").window('close');															    	 	
					}, 1500);
				}else if(pandasd==false){
					$(".drugoneb").text("入库数量不能为空");
			 		 //清空文本
			 		$("#DRUGONEb").window('open');
			  	 	//三秒之后自动消失
			   		setTimeout(function(){
			    	 	$("#DRUGONEb").window('close');															    	 	
					}, 1500);
				}else{
					rukus();
					if(panduan==false){
						tuiyaos();
					}
				}
		
				
				
			});	
			
			function rukus(){
				$("<form method='Post' id='for'>").appendTo("body").form({
					url:'save-inventory',
					onSubmit:function(param){
						//获取采购单号
						var indentid = $("#audit-cgdh").textbox("getValue");
						
						$.ajax({  
	                        url: 'update-indent',  
	                        data:{'indentid':indentid},
	                        type: 'POST',  
	                        dataType:"json",
						 	success: function (data) {  
						
						     }, 				     
	                        Error: function () {  
	                            alert(Error);  
	                        }                   
	                    });    
						
						//获取入库方式
						param["putin.inStorageType"] = 0;

						var shijan = CurentTime();
						//获取时间(--注意：这里要用时间的转换器--)
						param["putin.inStorageTime"] = shijan ;	
						
						//获取采购人
						param["putin.inStoragePeople"] = $("#audit-fzr").val();							
						
						//获取验收人
						param["putin.inStorageAcceptance"] = $("#indentPeople").val();	
						
						//获取表格中的采购的详情记录
						var rows = $("#inaudit-dg").datagrid("getRows");
						var total=0;
						var money=0;

						for (var i = 0; i < rows.length; i++) {
							//单个药品的入库数量                                                          
							param["putdetails["+i+"].inDetailsQuantity"] = rows[i]["in_details_quantity"];
							//药品库存编号
							param["putdetails["+i+"].Inventory.inventoryNumber"] = rows[i]["inventory_number"];
							//入库批次
							param["putdetails["+i+"].inDetailsBatch"] = rows[i]["drugbatch"];
						
							//药品的总数量
							total +=parseInt(rows[i]["in_details_quantity"]); 							
							
							//获取库存号
							var inventorynumber = rows[i]["inventory_number"];						
							//获取新库存数量
							var sum = rows[i]["in_details_quantity"];							
							$.ajax({  
			                       url: 'update-inven',  
			                       data:{
			                    	   'inventorynumber':inventorynumber,
			                    	   'sum':sum
			                       },
			                       type: 'POST',  
			                       dataType:"json",
								   success: function (data) {  
								
								   }, 				     
			                       Error: function () {  
			                           alert(Error);  
			                       }                   
			                });    
							
							//药品库存编号
							param["inventorydetails["+i+"].Inventory.inventoryNumber"] = rows[i]["inventory_number"];
							//新库存批次
							param["inventorydetails["+i+"].inventoryDetailsBatch"] = rows[i]["drugbatch"];
							//新库存数量
							param["inventorydetails["+i+"].inventoryDetailsQuantity"] = rows[i]["in_details_quantity"];
							//新库存生产日期						
							param["inventorydetails["+i+"].inventoryDetailsStardate"] = new Date(rows[i]["dataTime"]);
							//新库存有效日期
							var d = new Date(rows[i]["dataTime"]);
							d.setMonth(d.getMonth()+parseInt(rows[i]["drug_origin"]));
							param["inventorydetails["+i+"].inventoryDetailsUsedate"] = d ;
							
						}						
					
						//总数量
						param["putin.inStorageQuantity"] = parseInt(total);
						//总金额
						//param["Indent.indentAllmoney"] = money;
					},
					success:function(data){
						 if(parseInt(data)==1){
								$(".drugoneb").text("药品已经入库成功！");
							 	$("#DRUGONEb").window('open');
							 	$('#audit-dg').datagrid("reload");
						    	//三秒之后自动消失
							   	setTimeout(function(){
									$("#DRUGONEb").window('close');
									$('#inaudit-win').window("close");
								}, 2000);
							   
							    $('#for').form("clear");//清空文本
						}
							
						if(parseInt(data)==2){
						    	$(".drugoneb").text("入库失败,稍后重试......");
						 		 //清空文本
						 		$("#DRUGONEb").window('open');
						  	 	//三秒之后自动消失
						   		setTimeout(function(){
						    	 	$("#DRUGONEb").window('close');															    	 	
								}, 3000);
							
						}										
						
					}
				}).submit();
			}
			
			function tuiyaos(){
				$("<form method='Post' id='for'>").appendTo("body").form({
					url:'save-Return', 
					onSubmit:function(param){				
						//获取表格中的采购的详情记录
						var rows = $("#inaudit-dg").datagrid("getRows");
						
						//获取退药状态
						param["good.returnGoodsState"] =2;
						
						//获取供应商id
						param["good.supplier.supplierNumber"] = $("#audit-gyss").val();
						
						//退药获取负责人
						param["good.returnGoodsHead"] =$("#indentPeople").val() ;
						
						var shijan = CurentTime();
						//获取退药时间
						param["good.returnGoodsTime"] = shijan ;
						
						//获取退药原因
						param["good.returnGoodsReason"] ="采购退药" ;	
						var totals=0;
						var moneys=0;
						for (var i = 0; i < rows.length; i++) {							
							if(rows[i]["indent_details_quantity"] != rows[i]["in_details_quantity"]){
								//药品批次
								param["gooddetail["+i+"].returnDetailsPici"] = rows[i]["drugbatch"];
								//药品库存编号
								param["gooddetail["+i+"].inventory.inventoryNumber"] = rows[i]["inventory_number"];
								//采购退货数量
								param["gooddetail["+i+"].returnDetailsQuantity"] = rows[i]["indent_details_quantity"] - rows[i]["in_details_quantity"];								
							}
							//药品的总数量
							totals +=parseInt(rows[i]["indent_details_quantity"] - rows[i]["in_details_quantity"]); 
							//药品的总金额
							moneys +=rows[i]["drug_purchase_price"]*(rows[i]["indent_details_quantity"] - rows[i]["in_details_quantity"]);			
						}
						//退药总数量
						param["good.returnGoodsAllquantity"] = parseInt(totals);
						//退药总金额
						param["good.returnGoodsTotal"] = moneys;

					},
					success:function(data){
						 if(parseInt(data)==1){
								$(".drugoneq").text("退药申请成功！！！");
							 	$("#DRUGONEq").window('open');
							 	$('#audit-dg').datagrid("reload");
						    	//三秒之后自动消失
							   	setTimeout(function(){
									$("#DRUGONEq").window('close');
									$('#inaudit-win').window("close");
								}, 4000);
							   
							    $('#for').form("clear");//清空文本
						}									
						
					}
				}).submit();
			}
			

		});		
		
		//验证
		$.extend($.fn.textbox.defaults.rules, {
			    //数字验证
				sumyz: {
			        validator: function(value, param) {
			            var reg = /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/;
			            return reg.test(value);
			        },
			        message: "姓名请输入中文"
			    }
			    
	   	});
		
		$.extend($.fn.datagrid.methods, {
			editCell: function(jq,param){
				return jq.each(function(){
					var opts = $(this).datagrid('options');
					var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
					for(var i=0; i<fields.length; i++){
						var col = $(this).datagrid('getColumnOption', fields[i]);
						col.editor1 = col.editor;
						if (fields[i] != param.field){
							col.editor = null;
						}
					}
					$(this).datagrid('beginEdit', param.index);
					for(var i=0; i<fields.length; i++){
						var col = $(this).datagrid('getColumnOption', fields[i]);
						col.editor = col.editor1;
					}
				});
			}
		});
		
		var editIndex = undefined;
		function endEditing(){
			if (editIndex == undefined){return true}
			if ($('#inaudit-dg').datagrid('validateRow', editIndex)){
				$('#inaudit-dg').datagrid('endEdit', editIndex);
				editIndex = undefined;
				return true;
			} else {
				return false;
			}
		}
		function onClickCell(index, field){
			if (endEditing()){
				$('#inaudit-dg').datagrid('selectRow', index)
						.datagrid('editCell', {index:index,field:field});
				editIndex = index;
			}
		}
		
		// 时间戳
		function comFormatDate(date) {
			var day = new Date(date); 
			var Year = 0; 
			var Month = 0; 
			var Day = 0; 
			var CurrentDate = ""; 
			//初始化时间 
			Year= day.getFullYear();//ie火狐下都可以 
			Month= day.getMonth()+1; 
			Day = day.getDate(); 
			Hour = day.getHours(); 
			 Minute = day.getMinutes(); 
			 Second = day.getSeconds(); 
			CurrentDate += Year + "-"; 
			if (Month >= 10 ) { 
				CurrentDate += Month + "-"; 
			}else { 
				CurrentDate += "0" + Month + "-"; 
			} 
			if (Day >= 10 ) { 
				CurrentDate += Day ; 
			}else { 
				CurrentDate += "0" + Day ; 
			} 
			if(Hour>=10){
				CurrentDate +=" "+Hour;
			}else{
				CurrentDate +=" "+"0"+Hour;
			}
			if(Minute>=10){
				CurrentDate +=":"+Minute;
			}else{
				CurrentDate +=":"+"0"+Minute;
			}
			if(Second>=10){
				CurrentDate +=":"+Second;
			}else{
				CurrentDate +=":"+"0"+Second;
			}
			return CurrentDate; 
		}


	</script>

	<div id="audit-p" class="easyui-panel" style="width: 100%; height: 100%; padding: 10px; background: #fafafa;"
		data-options="iconCls:'icon-save',closable:true,collapsible:true,minimizable:true,maximizable:true">

		<!-- 药品验收窗口 -->
		<fieldset style="border: 1px solid #A6A6A6; border-radius: 6px; width: 1050px; margin: 0 auto; margin-top: 10px; margin-bottom: 20px;">
			
			<legend style="font-size: 17px">入库审核</legend>
			
			<table id="audit-dg" class="logininform-table easyui-datagrid" style="width: 1030; height: 308px"
				data-options="toolbar:'#logininform-tb',fitColumns:false,singleSelect:false">
			
			</table>
		
		</fieldset>
	
	</div>

	<!-- 入库窗口 -->
	<div id="inaudit-win" class="easyui-window" title="入库验收" style="width: 1100px; height: 550px"
		data-options="iconCls:'icon-save',modal:true,closed:true,shadow:true,resizable:false,collapsible:false,minimizable:false,maximizable:false">
		
		<div class="easyui-layout" data-options="fit:true">
			
			<div data-options="region:'center'">

				<div style="width: 1000px; height: 60px; line-height:60px;margin-left:50px;">
					
					<p>
						
						<input id="audit-cgdh" class="easyui-textbox" style="width: 200px" data-options="label:'采购单号：',readonly:true"></input>
						
						<span style="margin-left: 50px;"></span> 
						
						<input id="audit-cgsj" class="easyui-textbox" style="width: 200px" data-options="label:'总金额：',readonly:true"></input>
						
						<span style="margin-left: 50px;"></span> 						
						
						<input id="audit-fzr" class="easyui-textbox" style="width: 200px" data-options="label:'负责人：',readonly:true"></input>
						
						<span style="margin-left: 50px;"></span> 						
						
						<input id="audit-rukushij" class="easyui-textbox" style="width: 230px" data-options="label:'采购时间：',readonly:true"></input>
						
						<input id="audit-gyss" class="easyui-textbox" style="width: 200px" data-options="label:'供应商：',readonly:true"></input>
						
					</p>
				
				</div>
				
				<div style="margin-left: 17px;">
					
					<table id="inaudit-dg" class="logininform-table easyui-datagrid" style="width: 1050px; height: 308px"
						data-options="toolbar:'#logininform-tb',fitColumns:false,singleSelect:false,onClickCell: onClickCell">

					</table>
				
				</div>
				
				<p style="margin-left: 340px ; padding: 10px;" >
					
					<a id="save-audit" style="width: 100px" class="easyui-linkbutton" iconCls="icon-ok">确认收货</a>
					
					<span style="margin-left: 50px;"></span> 
					
					<a id="cancel-audit" style="width: 100px" class="easyui-linkbutton" iconCls="icon-cancel">取消</a>
				
				</p>
			
			</div>
		
		</div>
	
	</div>
	
	<input type="hidden" value="${user.userName}"  id="indentPeople">
	<!-- 弹框提示 -->
	<div id="DRUGONEb" class="easyui-window"  title="提示框" style="width:300px;height:156px"
	    data-options="iconCls:'icon-save',modal:true,resizable:false,collapsible:false,maximizable:false,minimizable:false,closed:true">
	          <p class="drugoneb" style="text-align:center;font-size: 16px;margin-top: 47px;">
	          </p>
	</div>
	<!-- 弹框提示 -->
	<div id="DRUGONEq" class="easyui-window"  title="提示框" style="width:300px;height:156px"
	    data-options="iconCls:'icon-save',modal:true,resizable:false,collapsible:false,maximizable:false,minimizable:false,closed:true">
	          <p class="drugoneq" style=" text-align:center;font-size: 16px;margin-top: 47px;">
	          </p>
	</div>
	
</body>
</html>